package com.example.edu.Service.ipml;

import com.example.edu.Entity.Tag;
import com.example.edu.Mapper.TagMapper;
import com.example.edu.Utils.CacheDataBaseUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.example.edu.Utils.Constants.TAG_KEY;

@Service
public class TagService {
    @Resource
    CacheDataBaseUtil cacheDataBaseUtil;
    @Resource
    TagMapper tagMapper;

    @Scheduled(cron = "0 32 4 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void cleanUnusedTag(){
        List<Tag> wild_tags = tagMapper.getWildTag();
        List<String> tag_names = new ArrayList<>();
        for(Tag wild_tag : wild_tags)
            tag_names.add(wild_tag.getTag_name());
        try{
            cacheDataBaseUtil.deleteManyById(TAG_KEY,tag_names,tag_names2 -> tagMapper.deleteByNames(tag_names2));
        }catch (Exception e){
            System.out.println(e);
            throw new RuntimeException();
        }
    }
}
